package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
)

// 定义全局db
var db *sql.DB

func main() {
	// 构建连接串
	dsn := "root:123456@tcp(localhost:3306)/go_demo"

	// 打开数据库连接
	var err error
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalln(err)
	}
	defer db.Close()

	ctx := context.Background()

	// 检查数据库连接是否成功
	err = db.PingContext(ctx)
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println("Connected to the database successfully!")

	fmt.Println("select once")
	one, err := getOne(2)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println(one)

	fmt.Println("select mutil")
	many, err := getMany(10)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println(many)

	fmt.Println("one update")
	one.name = "我更新了???"
	err = one.Update()
	if err != nil {
		log.Fatalln(err)
	}
	one1, _ := getOne(2)
	fmt.Println(one1)

	// 插入
	fmt.Println("insert")
	a := app{
		name: "ww44444ww",
	}
	err = a.Insert()
	if err != nil {
		log.Fatalln(err)
	}
	aCopy, err := getOne(a.ID)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println(aCopy)
}
